<template>
  <div
    ref="myChartsRef"
    :class="className"
    :style="{ height: height, width: width }"
    :option="option"
    class="myCharts"
  ></div>
</template>

<script setup lang="ts">
import { autoHover } from '@/utils/echartTool';
import {
  ref,
  watch,
  onMounted,
  onBeforeUnmount,
  withDefaults,
  defineProps,
} from "vue";
import { ECharts, EChartsOption, init } from 'echarts';

// 定义props
interface Props {
  className?: string;
  width?: string;
  height?: string;
  option: EChartsOption;
  carouselNum: number; // 滚动播放的数量
}
const props = withDefaults(defineProps<Props>(), {
  className: "chart",
  width: "100%",
  height: "100%",
  option: () => ({}),
});

const myChartsRef = ref<HTMLDivElement>();
let myChart: ECharts;
let timer: number;

const initChart = (): void => {
  if (myChart !== undefined) {
    myChart.dispose();
    // myChart.clear()
  }
  myChart = init(myChartsRef.value as HTMLDivElement);
  myChart?.setOption(props.option, false);
  autoHover(myChart, props.option, props.carouselNum, 3000);
};

const resizeChart = (): void => {
  // console.log('resizeChart')
  timer = window.setTimeout(() => {
    if (myChart) {
      myChart.resize();
    }
  }, 500);
};

onMounted(() => {
  initChart();
  window.addEventListener("resize", resizeChart);
  autoHover(myChart, props.option, props.carouselNum, 3000);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeChart);
  clearTimeout(timer);
  timer = 0;
});

watch(
  props.option,
  () => {
    initChart();
  },
  {
    deep: true,
  }
);

watch(
  () => props.carouselNum,
  () => {
    autoHover(myChart, props.option, props.carouselNum, 3000);
  },
  {
    deep: true
  }
);
</script>

<style lang="scss" scoped></style>
